package com.kindsoft.demo.services;

import java.util.*;
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ADUserService {

	private final Logger log = LoggerFactory.getLogger(getClass());

    @Value("${ldap.url}")
    private String ldapUrl;

    @Value("${ldap.base}")
    private String ldapBase;

    @Value("${ldap.userDn}")
    private String ldapUserDn;

    @Value("${ldap.userPwd}")
    private String ldapUserPwd;


	public List getUserNames() {
		List<String> list = new ArrayList<String>();
		NamingEnumeration results;
        try {
            Hashtable env = new Hashtable();
            env.put("java.naming.security.authentication", "simple");
            env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
            env.put("java.naming.provider.url", ldapUrl);
            env.put("java.naming.security.principal", ldapUserDn);
            env.put("java.naming.security.credentials", ldapUserPwd);
            LdapContext ctx = new InitialLdapContext(env, null);
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(2);
            String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
            String searchBase = ldapBase;
            String returnedAtts[] = {
                    "samaccountname", "userprincipalname"
            };
            searchControls.setReturningAttributes(returnedAtts);
            SearchResult searchResult;
            for (NamingEnumeration result = ctx.search(searchBase, searchFilter, searchControls); result.hasMoreElements();) {
                searchResult = (SearchResult) result.next();
                list.add(searchResult.getName());
                log.info((new StringBuilder()).append("<getUserNames> name: ").append(searchResult.getName()).toString());
            }
            ctx.close();
        }
        catch (Exception e) {
            log.error("<getUserNames> error: " + e.getMessage(), e);
            e.printStackTrace();
        }
//        } finally {
//            if (results != null) {
//                try {
//                    results.close();
//                }
//                // Misplaced declaration of an exception variable
//                catch (Exception ex)
//                {
//                    log.error("<getUserNames> error: " + ex.getMessage(), ex);
//                }
//            }
//        }
        return list;
	}
}
